package com.flyqiu.common.mybaits.plus.type;

import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


@MappedJdbcTypes(value = {JdbcType.VARCHAR, JdbcType.NVARCHAR, JdbcType.LONGVARCHAR})
@MappedTypes(JSONObject.class)
public class MyBaitsFastJson2ObjectHandler extends BaseTypeHandler<JSONObject> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, JSONObject jsonObject, JdbcType jdbcType) throws SQLException {
        String json = jsonObject.toJSONString();
        preparedStatement.setString(i, json);
    }

    @Override
    public JSONObject getNullableResult(ResultSet resultSet, String s) throws SQLException {
        if (resultSet == null) return null;
        String string = resultSet.getString(s);
        if (StringUtils.isEmpty(string)) return null;
        return JSONObject.parseObject(string);
    }

    @Override
    public JSONObject getNullableResult(ResultSet resultSet, int i) throws SQLException {
        if (resultSet == null) return null;
        String string = resultSet.getString(i);
        if (StringUtils.isEmpty(string)) return null;
        return JSONObject.parseObject(string);
    }

    @Override
    public JSONObject getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String string = callableStatement.getString(i);
        if (StringUtils.isEmpty(string)) return null;
        return JSONObject.parseObject(string);
    }
}
